﻿using System;
using System.IO;
using UnityEngine;
using USClientKernel.Template;
using XLua;

namespace Common.Utils
{
    public class XLuaManager : UGlobalSingleton<XLuaManager>
    {
        private LuaEnv m_pLuaEnv;

        protected override void Init()
        {
            m_pLuaEnv = new LuaEnv();
            m_pLuaEnv.AddLoader(CustomLoader);
        }


        public void ReloadMain()
        {
            try
            {
                if (m_pLuaEnv != null)
                {
                    m_pLuaEnv.DoString("package.loaded['Main'] = nil");
                }
            }
            catch (System.Exception ex)
            {
                string msg = string.Format("xLua exception : {0}\n {1}", ex.Message, ex.StackTrace);
                Debug.LogError(msg, null);
            }
            LoadMain();
        }


        void LoadMain()
        {
            try
            {
                if (m_pLuaEnv != null)
                {
                    m_pLuaEnv.DoString("require 'Main'");
                }
            }
            catch (System.Exception ex)
            {
                string msg = string.Format("xLua exception : {0}\n {1}", ex.Message, ex.StackTrace);
                Debug.LogError(msg, null);
            }
        }


        public static byte[] CustomLoader(ref string filepath)
        {
            Debug.Log("Load xLua script : " + filepath);

            // TODO：此处从项目资源管理器加载lua脚本
            string path = "Assets/Scripts/" + filepath.Replace(".", "/") + ".txt";

            TextAsset textAsset = (TextAsset)ResManager.Instance.Load(path);
            byte[]  buffer = textAsset.bytes;

            return buffer;
        }


        public void Update()
        {
            if (null != m_pLuaEnv)
                m_pLuaEnv.Tick();
        }

        /// <summary>
        /// 释放掉函数
        /// 此函数会在 OnDestroy 之前调用
        /// </summary>
        private void OnDisable()
        {
            if (null != m_pLuaEnv)
                m_pLuaEnv.DoString("require 'Dispose'");
        }

        public void OnDestroy()
        {
            if (null != m_pLuaEnv)
                m_pLuaEnv.Dispose();
        }


        public LuaEnv LuaEnv
        {
            get
            {
                return m_pLuaEnv;
            }

            set
            {
                m_pLuaEnv = value;
            }
        }
    }
}
